import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { CardService } from './card.service';
import { CardInput } from './dto/card.input.type';
import { CardType } from './dto/card.type';
import { GqlAuthGuard } from '@/common/guards/auth.guards';
import { UseGuards } from '@nestjs/common';
import {
  CARD_DEL_FAIL,
  CARD_NOT_EXIST,
  CARD_FAIL,
  CARD_CREATE_FAIL,
  SUCCESS,
  UPDATE_ERROR,
} from '@/common/constants/code';
import { CurUserId } from '@/common/decorators/current-user.decorator';
// import { PageInput } from '@/common/dto/page.input';
import { CardResult, CardResults } from './dto/card.output.type';
import { Result } from '@/common/dto/result.type';
import { Card } from './models/card.entity';
import { FindOptionsWhere, Like } from 'typeorm';
import { CurOrgId } from '@/common/decorators/current-org.decorator';

@Resolver(() => CardType)
@UseGuards(GqlAuthGuard) //启用守卫
export class CardResolver {
  constructor(private readonly cardService: CardService) {}

  @Query(() => CardResult, { description: '使用ID查询消费卡' })
  async getCardInfo(@Args('id') id: string): Promise<CardResult> {
    const result = await this.cardService.findById(id);
    if (result) {
      return {
        code: SUCCESS,
        data: result,
        message: '获取成功',
      };
    }
    return {
      code: CARD_NOT_EXIST,
      message: '消费卡不存在',
    };
  }
  // 将新增和修改合并到一个接口
  @Mutation(() => CardResult)
  async commitCard(
    @Args('params') params: CardInput,
    @Args('courseId') courseId: string,
    @CurUserId() userId: string,
    @CurOrgId() orgId: string,
    @Args('id', { nullable: true }) id?: string,
  ): Promise<Result> {
    if (id) {
      const card = await this.cardService.findById(id);
      if (!card) {
        return {
          code: CARD_NOT_EXIST,
          message: '消费卡信息不存在',
        };
      }
      const res = await this.cardService.updateById(id, {
        ...params,
        updateBy: userId,
      });
      if (res) {
        return {
          code: SUCCESS,
          message: '更新成功',
        };
      }
      return {
        code: UPDATE_ERROR,
        message: '更新失败',
      };
    }
    // 如果没有，那就创建
    const res = await this.cardService.create({
      ...params,
      createBy: userId,
      org: {
        id: orgId,
      },
      course: {
        id: courseId,
      },
    });
    if (res) {
      return {
        code: SUCCESS,
        message: '创建成功',
      };
    }
    return {
      code: CARD_CREATE_FAIL,
      message: '操作失败',
    };
  }
  // 获取多个实例
  @Query(() => CardResults)
  async getCards(
    // @Args('page') page: PageInput,
    @Args('courseId') courseId: string,
    @CurUserId() userId: string,
    @Args('name', { nullable: true }) name?: string,
  ): Promise<CardResults> {
    // const { pageNum, pageSize } = page;
    const where: FindOptionsWhere<Card> = {
      createBy: userId,
      course: { id: courseId },
    };
    if (name) {
      where.name = Like(`%${name}%`);
    }
    const [results] = await this.cardService.findCards({
      // start: (pageNum - 1) * pageSize,
      // size: pageSize,
      where,
    });
    return {
      code: SUCCESS,
      data: results,
      // page: {
      //   pageNum,
      //   pageSize,
      //   total,
      // },
      message: '获取成功',
    };
  }
  @Mutation(() => Boolean, { description: '新增' })
  async createCard(@Args('params') params: CardInput): Promise<boolean> {
    return await this.cardService.create(params);
  }
  @Mutation(() => Result, { description: '删除' })
  async deleteCard(
    @Args('id') id: string,
    @CurUserId() userId: string,
  ): Promise<Result> {
    const result = await this.cardService.findById(id);
    if (result) {
      const delRes = await this.cardService.deleteById(id, userId);
      if (delRes) {
        return {
          code: SUCCESS,
          message: '删除成功',
        };
      }
      return {
        code: CARD_DEL_FAIL,
        message: '删除失败',
      };
    }
    return {
      code: CARD_FAIL,
      message: '消费卡不存在',
    };
  }
  //   @Query(() => CardType, { description: '使用ID查询消费卡' })
  //   async find(@Args('id') id: string): Promise<CardType> {
  //     return await this.cardService.findById(id);
  //   }
  //   @Mutation(() => Boolean, { description: '更新消费卡' })
  //   async update(
  //     @Args('id') id: string,
  //     @Args('params') params: CardInput,
  //   ): Promise<boolean> {
  //     return await this.cardService.update(id, params);
  //   }
  //   @Mutation(() => Boolean, { description: '删除消费卡' })
  //   async del(@Args('id') id: string): Promise<boolean> {
  //     return await this.cardService.del(id);
  //   }
}
